﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using NHibernate;
using ZLCMS.Data.Model;
using NHibernate.Criterion;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Business.Util;
using Newtonsoft.Json;
using DotNet.Common.NHibernateUtil;
using System.Collections.Generic;
using System.Text;
//using ZLCMS.Business.Shop.Data;
using DotNet.Common.Command;
using ZLCMS.Commands.User.Commands.ProductSku;
using ZLCMS.Commands.Data;
namespace ZLCMS.Web.SystemManage.Basics.ProductSKU
{
    public partial class ProductSKUBatchAdd : System.Web.UI.Page
    {
        public ShopProductInfo product;
        protected List<ShopCategory> _list = new List<ShopCategory>();
        public FrameHelper _frameHelper { get; set; }
        public string _userAccount { get; set; }
        public string _productNo { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();
            _frameHelper = new FrameHelper(this);

            _productNo = Request["pno"] == null ? "" : Request["pno"];
            if (!string.IsNullOrEmpty((string)ViewState["pno"]))
            {
                _productNo = (string)ViewState["pno"];
            }
            else
            {
                ViewState["pno"] = _productNo;
            }

            using (var session = SessionFactoryHelper.CreateSession())
            {
                product = session.CreateCriteria<ShopProductInfo>().Add(Expression.Eq("ProductNo", _productNo)).UniqueResult<ShopProductInfo>();
            }
            if (Session[GlobalSessionString.CategoryIdBeforeModify] as string == product.TypeId.ToString())
            {
                _frameHelper.Alert(new ReturnCode()
                {
                    statusCode = 300,
                    message = "产品分类已修改!请先重置SKU!",
                    callbackType = "closeCurrent"
                });
            }
            else
            {
                if (!IsPostBack)
                    BindData();
                else
                    Save();
            }
        }

        /// <summary>
        /// 生成操作
        /// </summary>
        private void Save()
        {
            ICommandResult<UpdateSkuProductsResult> res = new UpdateSkuProductsCommand().Execute(new UpdateSkuProductsParameter()
    {
        ProductNo = _productNo,
        ProductSku = hid_product_sku.Value,
        SkuProJson = hid_sku_pro_jsonStr.Value
    });
            if (res.Error)
            {
                _frameHelper.Alert(new ReturnCode()
                {
                    statusCode = 300,
                    message = "操作失败!",
                    callbackType = "closeCurrent"
                });
            }
            else
            {
                _frameHelper.Alert(new ReturnCode()
                {
                    statusCode = 200,
                    message = "操作成功!",
                    callbackType = "closeCurrent"
                });
            }
        }



        private void BindData()
        {
            using (var session = SessionFactoryHelper.CreateSession())
            {
                var product = session.CreateCriteria<ShopProductInfo>().Add(Expression.Eq("ProductNo", _productNo)).UniqueResult<ShopProductInfo>();

                var groups = GetSkuGroups(session, product);

                grid.DataSource = groups;
                grid.DataBind();

                rpt_sku_product.DataSource = session.CreateCriteria<ShopSkuProduct>().Add(Expression.Eq("ProductNo", _productNo)).List<ShopSkuProduct>();
                rpt_sku_product.DataBind();
            }
        }

        #region 取得所有sku组 GetSkuGroups
        /// <summary>
        /// 取得所有sku组
        /// </summary>
        /// <param name="session"></param>
        /// <param name="category"></param>
        /// <returns></returns>
        private IList<ShopSkuGroup> GetSkuGroups(ISession session, ShopProductInfo product)
        {
            if (!string.IsNullOrEmpty(product.CustomField) && product.CustomField != "[]")
            {
                var CustomData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustomData>>(product.CustomField);

                if (CustomData != null)
                    return CustomData.Select(c => c.Group).ToList();
            }
            return new List<ShopSkuGroup>(); ;
        }
        #endregion

        /// <summary>
        /// 显示选择框
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        /// 
        protected string ShowCheckbox(object oid)
        {
            StringBuilder sb = new StringBuilder();
            int id = Convert.ToInt32(oid);
            using (var session = SessionFactoryHelper.CreateSession())
            {
                var list = session.CreateCriteria<ShopSkuItem>().Add(Expression.Eq("SkuGroupId", id)).List<ShopSkuItem>();
                foreach (var item in list)
                {
                    string sid = "ckb_" + id + "_" + item.Id;
                    sb.Append("<label for='cbk_" + item.Id + "'><input type='checkbox' " + IsExistGroupItem(item.Id) + " id='cbk_" + item.Id + "' onclick='SelectItem(this)'   itemname='" + item.ItemName + "' groupid='" + id + "'   value='" + item.Id + "' name='" + "ckb_" + id + "' id='" + sid + "' />" + item.ItemName + "</label>");
                }
            }
            return sb.ToString();
        }

        /// <summary>
        /// 判断在产品是存在该skuItem
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string IsExistGroupItem(int id)
        {
            List<CustomData> customData = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CustomData>>(product.CustomField);
            bool flage = false;
            foreach (CustomData c in customData)
            {
                foreach (ShopSkuItem item in c.Items)
                {
                    if (item.Id == id)
                    {
                        flage = true;
                    }
                }
            }
            if (flage == true)
            {
                return " checked='checked  '";
            }
            else
            {
                return "";
            }
        }

        public string GetSkuGroupHtml()
        {
            using (var session = SessionFactoryHelper.CreateSession())
            {
                IList<ShopSkuGroup> groups = GetSkuGroups(session, product);
                string groupsHtml = "";
                foreach (ShopSkuGroup group in groups)
                {
                    groupsHtml += "<th  >" + group.SkuName + "</th>";
                }
                return groupsHtml;
            }

        }

        public string GetSkuItemHtml(string paramCode)
        {
            List<SKUGroup> groupItems = Newtonsoft.Json.JsonConvert.DeserializeObject<List<SKUGroup>>(paramCode);
            string skuItemHtml = "";
            foreach (SKUGroup item in groupItems)
            {
                skuItemHtml += "<td   groupname='" + item.GroupName + "' itemname='" + item.ItemName + "' groupid='" + item.GroupId + "' itemid='" + item.ItemId + "'>" + item.ItemName + "</td>";
            }
            return skuItemHtml;
        }


    }

    /// <summary>
    /// 用于计算
    /// </summary>
    public class Node
    {
        public Node Parent { get; set; }
        public List<Node> Nodes { get; set; }
        public ShopSkuItem Item { get; set; }
    }
}